package com.zut.edu;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.internal.NavigationMenuView;
import com.google.android.material.navigation.NavigationView;
import com.michaldrabik.tapbarmenulib.TapBarMenu;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;
import com.zut.edu.bean.Company;
import com.zut.edu.bean.Page;
import com.zut.edu.fragment.FragmentAdapter;
import com.zut.edu.fragment.ReadFragment;
import com.zut.edu.fragment.WriteFragment;
import com.zut.edu.http.BaseCallback;
import com.zut.edu.http.OkhttpHelper;
import com.zut.edu.utils.CameraUtils;
import com.zut.edu.utils.StringUtils;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

public class MainOpActivity extends AppCompatActivity implements View.OnClickListener{

    @BindView(R.id.mainop_topbar)
    QMUITopBarLayout maintopbar;//顶部条
    @BindView(R.id.mainop_topbar_user_head)
    QMUIRadiusImageView topbaruserhead;//头像
    @BindView(R.id.mainop_drawerLayout)
    DrawerLayout drawerLayout;//侧拉抽屉
    @BindView(R.id.mainop_left_navigation)
    NavigationView leftnavigation;
    @BindView(R.id.mainop_bottom_navigation)
    BottomNavigationView bottomnavigation;
    @BindView(R.id.mainop_bottom_viewpager)
    ViewPager bottomviewpager;
    @BindView(R.id.mainop_main_tapBarMenu)
    TapBarMenu maintapBarMenu;
    @BindView(R.id.mainop_location_text)
    TextView locationtext;
    @BindView(R.id.mainop_item1)
    ImageView item1;
    @BindView(R.id.mainop_item2)
    ImageView item2;
    @BindView(R.id.mainop_item3)
    ImageView item3;

    AMapLocationClient mLocationClient = null;
    AMapLocationListener mLocationListener = new MyAMapLocationListener();
    AMapLocationClientOption mLocationOption = null;
    private static final int PHOTORESULT = 3;// 结果
    private QMUIRadiusImageView draweruserhead;
    private TextView draweruserName;
    private String userIdentity;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mainop);//  View root = LayoutInflater.from(this).inflate(R.layout.activity_drawer, null);//        setContentView(root);
        preJudge();
        ButterKnife.bind(this);
        QMUIStatusBarHelper.translucent(this);//沉浸式
        View headerView = leftnavigation.getHeaderView(0);
        draweruserhead = headerView.findViewById(R.id.drawer_user_head);
        draweruserName = headerView.findViewById(R.id.drawer_user_name);
        userIdentity = StringUtils.getLocalitem(this,"user","userIdentity");
        setListener();
        initTopBar();
        initLeft();
        initBottom();
        initLocation();
    }

    public void setListener(){
        topbaruserhead.setOnClickListener(this);
        maintapBarMenu.setOnClickListener(this);
        maintapBarMenu.setButtonMarginRight(25);
        item1.setOnClickListener(this);
        item2.setOnClickListener(this);
        item3.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.mainop_topbar_user_head:
                drawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.mainop_main_tapBarMenu:
                maintapBarMenu.toggle();
                break;
            case R.id.mainop_item1:
                final String[] item1 = new String[]{"写入无加密", "AES加密", "DES加密"};
                final int checkedIndex = Integer.valueOf(StringUtils.getLocalString(MainOpActivity.this,"lock"));
                new QMUIDialog.CheckableDialogBuilder(this)
                        .setCheckedIndex(checkedIndex)
                        .setSkinManager(QMUISkinManager.defaultInstance(this))
                        .addItems(item1, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                StringUtils.postLocalString(MainOpActivity.this,String.valueOf(which),"lock");
                                dialog.dismiss();
                                Toast.makeText(MainOpActivity.this,item1[which]+"设置成功",Toast.LENGTH_SHORT).show();
                            }
                        })
                        .create(R.style.QMUI_Dialog).show();
                break;
            case R.id.mainop_item2:
                final String[] item2 = new String[]{"关闭震动", "开启震动"};
                final int checkedIndex2 = Integer.valueOf(StringUtils.getLocalString(MainOpActivity.this,"shock"));
                new QMUIDialog.CheckableDialogBuilder(this)
                        .setCheckedIndex(checkedIndex2)
                        .setSkinManager(QMUISkinManager.defaultInstance(this))
                        .addItems(item2, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                StringUtils.postLocalString(MainOpActivity.this,String.valueOf(which),"shock");
                                dialog.dismiss();
                                Toast.makeText(MainOpActivity.this,item2[which]+"设置成功",Toast.LENGTH_SHORT).show();
                            }
                        })
                        .create(R.style.QMUI_Dialog).show();
                break;
            case R.id.mainop_item3:
                final String[] item3 = new String[]{"关闭提示语音", "开启提示语音"};
                final int checkedIndex3 = Integer.valueOf(StringUtils.getLocalString(MainOpActivity.this,"volume"));
                new QMUIDialog.CheckableDialogBuilder(this)
                        .setCheckedIndex(checkedIndex3)
                        .setSkinManager(QMUISkinManager.defaultInstance(this))
                        .addItems(item3, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                StringUtils.postLocalString(MainOpActivity.this,String.valueOf(which),"volume");
                                dialog.dismiss();
                                Toast.makeText(MainOpActivity.this,item3[which]+"设置成功",Toast.LENGTH_SHORT).show();
                            }
                        })
                        .create(R.style.QMUI_Dialog).show();
                break;

        }
    }


    public void initTopBar(){//生成顶部条
        CameraUtils.initRadiusImageView(topbaruserhead,R.mipmap.user_head);
        StringUtils.photoURL(MainOpActivity.this,StringUtils.getLocalitem(this,"user","userPhoto"),topbaruserhead);
        switch (userIdentity){
            case "2":maintopbar.setTitle("产品追溯").setTextColor(ContextCompat.getColor(this,R.color.qmui_config_color_white));
            break;
            default:maintopbar.setTitle("产品写入").setTextColor(ContextCompat.getColor(this,R.color.qmui_config_color_white));
        }

    }

    public void initLeft(){//生成侧拉导航栏内容
        CameraUtils.initRadiusImageView(draweruserhead,R.mipmap.user_head);
        StringUtils.photoURL(MainOpActivity.this,StringUtils.getLocalitem(this,"user","userPhoto"),draweruserhead);
        draweruserName.setText(StringUtils.getLocalitem(this,"user","userName"));
        draweruserhead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CameraUtils.startPhotoAlbum(MainOpActivity.this);
            }
        });

        NavigationMenuView navigationMenuView = (NavigationMenuView) leftnavigation.getChildAt(0);
        if (navigationMenuView != null) {
            navigationMenuView.setVerticalScrollBarEnabled(false);
        }
        leftnavigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()){
                    case R.id.mainop_left_menu_item1:
                        Intent queryrecord = new Intent(MainOpActivity.this, MineActivity.class);
                        startActivity(queryrecord);
                        break;
                    case R.id.mainop_left_menu_item2:
                        Intent encryption = new Intent(MainOpActivity.this,QueryTagActivity.class);
                        startActivity(encryption);
                        break;
                    case R.id.mainop_left_menu_model:
                        Intent intent6 = new Intent(MainOpActivity.this, AboutActivity.class);
                        startActivity(intent6);
                        break;
                    case R.id.mainop_left_menu_quit:
                        quitJudge();
                        break;

                }
                item.setCheckable(false);
            //    drawerLayout.closeDrawer(GravityCompat.START);
                return true;
            }
        });

    }

    public void initBottom(){//生成底部导航栏+页面
        List<Fragment> fragments = new ArrayList<>();
        switch (userIdentity){
            case "2":fragments.add(new ReadFragment());
            break;
            default:fragments.add(new WriteFragment());
            break;
        }
        FragmentAdapter adapter = new FragmentAdapter(fragments, getSupportFragmentManager());
        bottomviewpager.setAdapter(adapter);

//        bottomnavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
//            @Override
//            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {//点击跳转页面
//
//                switch (menuItem.getItemId()) {
//                    case R.id.bottom_menu_item1:
//                        bottomviewpager.setCurrentItem(0);
//                        maintopbar.setTitle("写入").setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.qmui_config_color_white));
//                        break;
//                    case R.id.bottom_menu_item2:
//                        bottomviewpager.setCurrentItem(1);
//                        maintopbar.setTitle("追溯").setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.qmui_config_color_white));
//                        break;
//                }
//                return false;
//            }
//        });
//
//        bottomviewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {//滑动跳转页面
//            @Override
//            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//            }
//
//            @Override
//            public void onPageSelected(int position) {
//                bottomnavigation.getMenu().getItem(position).setChecked(true);
//                switch (position){
//                    case 0:
//                        maintopbar.setTitle("写入").setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.qmui_config_color_white));
//                        break;
//                    case 1:
//                        maintopbar.setTitle("追溯").setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.qmui_config_color_white));
//                        break;
//                }
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//
//            }
//        });


    }



    private void preJudge(){
        SharedPreferences sp = getSharedPreferences("nfc_pre",MODE_PRIVATE);
        String user_data = sp.getString("user","");
        Log.e("user",user_data);
        if(StringUtils.isEmpty(user_data)){
            Intent intent = new Intent(this,LoginActivity.class);
            startActivity(intent);
            finish();
        }
        else initCompany(StringUtils.BASE_URL+"/company/query");

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {//实时监听,多次执行,分类requestCode,判断handleResultFromCameraOrPhotos
        super.onActivityResult(requestCode, resultCode, data);
        Object[] hash = new Object[2];
        if(requestCode==PHOTORESULT) {
            hash = CameraUtils.handleResultFromCameraOrPhotos(MainOpActivity.this,requestCode,resultCode,data);
            if(hash!=null){
                draweruserhead.setImageBitmap((Bitmap) hash[1]);
                topbaruserhead.setImageBitmap((Bitmap) hash[1]);
                updateUserHead(new File((String) hash[0]));
            }
        }
        else CameraUtils.handleResultFromCameraOrPhotos(MainOpActivity.this,requestCode,resultCode,data);

    }
    private void quitJudge() {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("退出")
                .setMessage("你确定要退出吗？")
                .setSkinManager(QMUISkinManager.defaultInstance(this))
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "退出", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        StringUtils.basicUninstall(MainOpActivity.this);
                        Intent quit = new Intent(MainOpActivity.this,LoginActivity.class);
                        quit.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(quit);
                    }
                })
                .create(R.style.QMUI_Dialog).show();
    }

    private void initCompany(String url){
        OkhttpHelper okhttpHelper = OkhttpHelper.getInstance();
        Map<String,Object> params = new HashMap<>(1);
        params.put("companyId",StringUtils.getLocalitem(this,"user","companyId"));
        okhttpHelper.get(url, params, new BaseCallback<Page<Company>>() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("onFailure", String.valueOf(e));
            }

            @Override
            public void onSuccess(@NotNull Call call, @NotNull Response response, Page<Company> companyPage, int code) throws IOException {
                StringUtils.postLocalObject(MainOpActivity.this,companyPage.getList().get(0),"company");
            }

            @Override
            public void onError(@NotNull Call call, @NotNull Response response, int code, Exception e) {
                Log.e("onError", String.valueOf(response));
                if(e!=null) Log.e("e", String.valueOf(e));
            }
        });
    }

    public void updateUserHead(File file)
    {
        if (!file.exists())
        {
            Toast.makeText(MainOpActivity.this, "文件不存在，请修改文件路径", Toast.LENGTH_SHORT).show();
            return;
        }
        String ts = String.valueOf(System.currentTimeMillis());
        String id = "28502";
        String token = "011d4d028c3a4164b76d516a5c151187";
        String sign = null;
        try {
            sign = StringUtils.MD5(id+"-"+token+"-"+ts);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("MD5",sign);
        Map<String, String> params = new HashMap<>();
        params.put("id",id);
        params.put("ts",ts);
        params.put("sign",sign);
        OkHttpUtils.post()//
                .addFile("image", "messenger_01.png", file)//
                .url("https://api.superbed.cn/upload")
                .params(params)//
                .build()//
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String resultStr = response.body().string();
                        String userPhoto = JSON.parseObject(resultStr).getString("url");
                        postUserHead(userPhoto);
                        Log.e("body",resultStr);
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("UserHead_E",String.valueOf(e));
                    }

                    @Override
                    public void onResponse(Object response, int id) {
                    }
                });
    }

    private void postUserHead(String userPhoto){
        OkhttpHelper okhttpHelper = OkhttpHelper.getInstance();
        Map<String,Object>params = new HashMap<>(2);
        params.put("userId",StringUtils.getLocalitem(this,"user","userId"));
        params.put("userPhoto",userPhoto);
        okhttpHelper.post(StringUtils.BASE_URL+"/user/update", params, new BaseCallback<String>() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("onFailure", String.valueOf(e));
            }

            @Override
            public void onSuccess(@NotNull Call call, @NotNull Response response, String s, int code) throws IOException {
                Log.e("onSuccess", String.valueOf(s));
            }

            @Override
            public void onError(@NotNull Call call, @NotNull Response response, int code, Exception e) {
                Log.e("onError", String.valueOf(response));
            }
        });
    }


    private void initLocation(){
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(false);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    class MyAMapLocationListener implements AMapLocationListener {

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    Log.e("位置",aMapLocation.getAddress());
                    StringUtils.postLocalString(MainOpActivity.this,aMapLocation.getProvince()+aMapLocation.getCity(),"location");
                    locationtext.setText(aMapLocation.getCity());
                    mLocationClient.stopLocation();
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    }


}
